"ui";
// require("./去限制.js");
const Config = require("./config")
var Util = require("./util.js");
var Dylntent = require("./DyIntent");
var state = 0
var yxcs = 0
var yxjd = 0
var jihuo
var preState = 0
var waitFollowIdList = []
var IsAddChar = true
var curList = []
var guanZhuList = []
var isClearHT = false;
var isRename = true;
var curLoginName = ""
var basePath = files.getSdcardPath() + "/皮卡qiu/"
var fname1 = basePath + "今日全部数据.txt";
var fname2 = basePath + "已关注数据.txt";
var yanghaoJs = null;
let pk = 2
var IsPinglun = true
var IsDianZan = true
var settingStorage
var PingLunContent = []
var PinLunGaiLv = 60
var DianZanGaiLv = 60
var downUrl = null
var lastedVersion = null
var deviceWidth = device.width;
var deviecHeight = device.height;
var floatyW = null // 悬浮窗
var controlPopWinJs = null //悬浮控制台
var StopTime = 5 //每个关注暂停时间
var Zdybz = null;
let intYY = 1;
var 控制台悬浮窗 = null
var color = "#009688";
var InitDataSuccess = false
let coffee = 2
var uidUser;
//var smallPic = images.read(plFSBtn)
// if (!requestScreenCapture()) {
//     toastLog("请求截图权限 失败");
//   } else {
//     toastLog("请求截图权限 成功");
// }
var dyVersion = "17.8.0"
var dyIdConfig = null

ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="皮卡qiu-火山版" />
                <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
                <frame>
                    <vertical marginTop="5">
                        <card w="*" h="42" margin="10 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                            <vertical padding="18 8" h="auto">
                                {/* <text text="[应用权限]" color="#FFA500" textStyle="bold" textSize="10sp" /> */}
                                <linear>
                                    <Switch margin="12 0" layout_weight="1" id="autoService" text="无障碍服务" textSize="10sp" checked="{{auto.service != null}}" />
                                    {/* <Switch margin="12 0" layout_weight="1" id="floatyService" text="悬浮窗权限" textSize="10sp" checked="{{floaty.checkPermission() != false}}" /> */}
                                    <Switch margin="12 0" layout_weight="1" id="floatyService" text="悬浮窗权限" textSize="10sp" checked="{{auto.service != null}}" />
                                </linear>
                            </vertical>
                            <View bg="#000000" h="*" w="5" />
                        </card>
                        <card w="*" h="55" marginLeft="10" marginRight="10" marginBottom="10" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                            <vertical padding="18 8" h="auto">
                                <linear>
                                    <text textSize="10sp" text="授权码:" textColor="black" w="auto" textStyle="bold" />
                                    <input textSize="10sp" id="kamiInput" color="#666666" paddingLeft="5" w="160" />
                                    <card w="48" h="32" margin="5 5" cardCornerRadius="2dp" cardElevation="2dp" gravity="center_vertical">
                                        <button id="loginBtn" h="*" text="激 活" textSize="10sp" textStyle="bold" color="#FFFFFF" bg="#00BFFF" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                        <View bg="#4EBFDD" h="*" w="5" />
                                    </card>
                                    <card w="48" h="32" margin="5 5" cardCornerRadius="2dp" cardElevation="2dp" gravity="center_vertical">
                                        <button id="jiebang" h="*" text="解 绑" textSize="10sp" textStyle="bold" color="#FFFFFF" bg="#00BFFF" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                        <View bg="#4EBFDD" h="*" w="5" />
                                    </card>
                                </linear>
                            </vertical>
                            <View bg="#FF0000" h="*" w="5" />
                        </card>
                        <scroll id='scroll0' w="*" h="255" fillViewport="true">
                            <vertical>
                                <card w="*" h="75" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <vertical padding="18 8" h="auto">
                                        <Switch id="clearHT" margin="2 5" layout_weight="1" text="定时清理运行后台(开启可防止应用无响应,运行更流畅)" checked="false" textSize="10sp" />
                                        <linear>
                                            <text text="清理功能必须先锁定脚本运行后台!点击旁边按钮去锁定>>>" color="#FF0000" textStyle="bold" textSize="10sp" />
                                            <card w="33" h="15" margin="5 5" cardCornerRadius="8dp" cardElevation="2dp" gravity="center_vertical">
                                                <button id="sdht" h="*" text="" textSize="8sp" textStyle="bold" color="#FFFFFF" bg="#FF6347" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                                <View bg="#4EBFDD" h="*" w="5" />
                                            </card>
                                        </linear>
                                    </vertical>
                                    <View bg="#FF6347" h="*" w="5" />
                                </card>
                                <vertical>
                                    <card w="*" h="auto" fillViewport="true" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">

                                        <vertical padding="18 8" h="auto">
                                            <text text="[功能选择]" color="#FFA500" textStyle="bold" textSize="10sp" />
                                            <linear>
                                                <Switch id="isRename" margin="2 0" layout_weight="1" text="用户备注" checked="true" textSize="10sp" />
                                                <Switch id="openPinglun" margin="2 0" layout_weight="1" text="作品评论" checked="true" textSize="10sp" />
                                            </linear>
                                            <linear>
                                                <Switch id="openDianzan" margin="2 0" layout_weight="1" text="作品点赞" checked="true" textSize="10sp" />
                                                <Switch id="test" margin="2 0" layout_weight="1" text="牛逼牛逼" checked="true" textSize="10sp" />
                                            </linear>
                                            <text text="[附加选择]" color="#FFA500" textStyle="bold" textSize="10sp" marginTop="12" />
                                            <linear>
                                                <text text="自定义备注内容" textStyle="bold" textSize="10sp" />
                                                <input id="ZDYBZ" hint="留空则默认备注:日期+昵称" marginRight="10" text="" textSize="10sp" color="#666666" w="150" />
                                            </linear>
                                            <text text="[功能设置]" color="#FFA500" textStyle="bold" textSize="10sp" marginTop="12" />
                                            <horizontal>
                                                <text text="评论概率" textStyle="bold" textSize="10sp" />
                                                <input id="plGL" marginRight="10" text="60" textSize="10sp" color="#666666" w="40" />
                                                <text text="点赞概率" textStyle="bold" textSize="10sp" />
                                                <input id="dzGL" marginRight="10" text="60" textSize="10sp" color="#666666" w="40" />
                                                <text text="间隔时间(秒)" textStyle="bold" textSize="10sp" />
                                                <input id="stopTimeInput" text="5" textSize="10sp" color="#666666" w="40" />
                                            </horizontal>
                                        </vertical>
                                        <View bg="#4EBFDD" h="*" w="5" />
                                    </card>
                                </vertical>

                                <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <vertical padding="18 8" marginBottom="2" h="auto">
                                        <text text="[评论设置]" color="#FFA500" textStyle="bold" textSize="10sp" />
                                        <horizontal>
                                            <text text="评论文案:" textStyle="bold" textSize="10sp" />
                                            <input id="plStr" textSize="10sp" textImeMultiLine="true" textMultiLine="true" color="#666666" w="*" />
                                        </horizontal>
                                        <text text="注：多条评论话术用换行输入,随机选择一条发送" color="#D2B48C" textStyle="bold" textSize="10sp" />
                                        <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                            <button id="yijianMoren" h="auto" text="生成默认文案" textSize="10" textStyle="bold" color="#ffffff" bg="#4EBFDD" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                            <View bg="#4EBFDD" h="*" w="5" />
                                        </card>
                                    </vertical>
                                    <View bg="#4EBFDD" h="*" w="5" />
                                </card>

                                <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <vertical padding="18 8" marginBottom="2" h="auto">
                                        <text text="[数据设置]" color="#FFA500" textStyle="bold" textSize="10sp" />
                                        <scroll h="100" fillViewport="true">
                                            <horizontal>
                                                <text text="uid数据:" textStyle="bold" textSize="10sp" />
                                                <input id="idStr" textSize="10sp" textImeMultiLine="true" textMultiLine="true" color="#666666" w="*" />
                                            </horizontal>
                                        </scroll>
                                        <linear>
                                            <text text="注：多条数据用换行输入" color="#D2B48C" textStyle="bold" textSize="10sp" />
                                        </linear>
                                    </vertical>
                                    <View bg="#4EBFDD" h="*" w="5" />
                                </card>
                            </vertical>
                        </scroll >
                        <card w="*" h="130" margin="10 5" cardCornerRadius="0dp" cardElevation="0dp" gravity="center_vertical">
                            <vertical w="*" h="auto" margin="10 0" >
                                <linear>
                                    <card w="150" h="40" margin="5 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                        <button id="start" h="*" text="正 常 启 动" textSize="10sp" textStyle="bold" color="#ffffff" bg="#1E90FF" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                        <View bg="#1E90FF" h="*" w="5" />
                                    </card>
                                    <card w="150" h="40" margin="5 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                        <button id="yijianSave" h="auto" text="保 存 配 置" textSize="10sp" textStyle="bold" color="#ffffff" bg="#1E90FF" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                        <View bg="#1E90FF" h="*" w="5" />
                                    </card>
                                </linear>
                                <text id="versionText" text="" textStyle="bold" textSize="10sp" marginTop="20" marginLeft="45" />
                            </vertical>
                            <View bg="#4EBFDD" h="*" w="0" />
                        </card>

                    </vertical >
                </frame>
                <frame>
                    <frame w="*" h="350" gravity="center">
                        <webview id="webview" w="360" h="360" />
                    </frame>
                    <card w="*" h="133" margin="10 355" cardCornerRadius="0dp" cardElevation="0dp" gravity="center_vertical">
                        <vertical w="*" h="auto" margin="10 0" >
                            <linear>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="KMD" h="*" text="开启悬浮窗权限教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="KMW" h="*" text="开启无障碍权限教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="KMM" h="*" text="锁定脚本后台教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                            </linear>
                            <linear>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="CJJC" h="*" text="采集功能使用教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="GZJC" h="*" text="关注功能使用教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="AJYCJC" h="*" text="虚拟按键隐藏教程" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                            </linear>
                            <linear>
                                <card w="98" h="40" margin="5 2" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                                    <button id="LMJJ" h="*" text="采集乱码解决方法" textSize="10sp" textStyle="bold" color="#ffffff" bg="#FF8C00" foreground="?selectableItemBackground" layout_gravity="bottom" />
                                    <View bg="#1E90FF" h="*" w="5" />
                                </card>
                            </linear>
                            <text id="versionText" text="" textStyle="bold" textSize="10sp" marginTop="20" marginLeft="45" />
                        </vertical>
                        <View bg="#4EBFDD" h="*" w="0" />
                    </card>
                </frame>
            </viewpager>
        </vertical>
        <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="https://ncstatic.clewm.net/rsrc/2022/0204/00/904840d2178517be752c9ab027759d73.jpg" />
            {/* http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg */}
            <list id="menu">
                <horizontal bg="?selectableItemBackground" w="*">
                    <img w="50" h="50" padding="16" src="{{this.icon}}" tint="{{color}}" />
                    <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center" />
                </horizontal>
            </list>
        </vertical>
    </drawer>
);

InitData()
打开控制台悬浮窗()

ui.clearHT.on("check", function (checked) {
    isClearHT = checked
    settingStorage.put(Config.OpenClearHT, isClearHT)
})
ui.isRename.on("check", function (checked) {
    isRename = checked
    settingStorage.put(Config.OpenBeiZhu, isRename)
})
ui.openPinglun.on("check", function (checked) {
    IsPinglun = checked
    settingStorage.put(Config.OpenPingLun, IsPinglun)
})
ui.openDianzan.on("check", function (checked) {
    IsDianZan = checked
    settingStorage.put(Config.OpenDianZan, IsDianZan)
})

ui.sdht.click(function () {
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }
    threads.start(function () {
        recents()
    })
})
//开启无障碍权限
ui.autoService.on("check", function (checked) {
    if (auto.service == null) {
        toast("请开启无障碍权限")
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    } else {
        auto.service.disableSelf();
        toast("无障碍权限已关闭")
    }

});

//开始关注点赞私信评论
ui.start.on("click", function () {
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }
    if (jihuo != 0) {
        toast("请先激活卡密！");
        return;
    }
    guanzhuThread = threads.start(function () {
        关注点赞私信评论();
        // test()
    });

});

function test() {
    Dylntent.gotoUserProfileHS(67722110505);
}

ui.yijianMoren.click(function () {
    默认私信评论()
})

ui.yijianSave.click(function () {
    设置概率();
    设置评论();
    设置数据();
})

function 设置概率() {
    var plglstr = ui.plGL.getText().toString().trim()
    PinLunGaiLv = parseInt(plglstr)
    var dzglstr = ui.dzGL.getText().toString().trim()
    DianZanGaiLv = parseInt(dzglstr)
    var stopTimeStr = ui.stopTimeInput.getText().toString().trim()
    StopTime = parseInt(stopTimeStr)
    Zdybz = ui.ZDYBZ.getText().toString().trim()
    settingStorage.put(Config.PinLunGaiLvKey, PinLunGaiLv)
    settingStorage.put(Config.DianZanGaiLvKey, DianZanGaiLv)
    settingStorage.put(Config.StopTime, StopTime)
    settingStorage.put(Config.Zdybz, Zdybz)
    console.log("功能设置成功")
}

function 设置评论() {
    var str = ui.plStr.getText().toString()
    settingStorage.put(Config.PingLunWenAn, str)
    var strList = str.split("\n")
    if (strList && strList.length > 0) {
        PingLunContent = []
        for (var i = 0; i < strList.length; i++) {
            PingLunContent.push(strList[i].trim())
        }
    }
    console.log("评论设置成功")
}


function 设置数据() {
    var shuju = ui.idStr.getText()
    if (shuju == null || typeof (shuju) == "undefined") {
        alert("输入的数据为空")
        return
    }
    var shujuList = shuju.toString().trim().split("\n");
    setTimeout(function () {
        console.log("当前已输入账号数据" + shujuList.length + "条")
    }, 1000)

    waitFollowIdList = []
    for (var i = 0; i < shujuList.length; i++) {
        waitFollowIdList.push(shujuList[i].trim())
    }
    files.write(fname1, shuju.toString().trim())
    console.log("数据设置成功")
}


function 默认私信评论() {
    confirm("确定使用默认文案吗？").then(value => {
        if (value) {
            var plList = Config.PinglunContent
            var tempPlStr = ""
            for (var i = 0; i < plList.length; i++) {
                if (i == plList.length - 1) {
                    tempPlStr = tempPlStr + plList[i]
                } else {
                    tempPlStr = tempPlStr + plList[i] + "\n"
                }
            }
            ui.plStr.setText(tempPlStr)
            settingStorage.put(Config.PingLunWenAn, tempPlStr)
            PingLunContent = []
            for (var i = 0; i < plList.length; i++) {
                PingLunContent.push(plList[i].trim())
            }
        }
    })
}


function SaveData2(hgIdList, fname) {
    var hxgzStr = ""
    for (var i = 0; i < hgIdList.length; i++) {
        if (i == hgIdList.length - 1) {
            hxgzStr = hxgzStr + hgIdList[i]
        } else {
            hxgzStr = hxgzStr + hgIdList[i] + "\n"
        }
    }
    files.write(fname, hxgzStr, [encoding = "utf-8"])
}



//关注私信点赞评论
function 关注点赞私信评论() {
    try {
        if (!InitDataSuccess) {
            console.log("初始化失败")
            return
        }
        device.keepScreenOn()
        var dyName = getPackageName("抖音");
        var dyhsName = getPackageName("抖音火山版");
        if (isClearHT) {
            console.error("**********温馨提示*********")
            console.info("即将自动清理运行后台......")
            toast("请确保脚本已锁定运行后台!如还未锁定,请观看脚本中的[锁定脚本运行后台]视频教程!")
            console.info("请确保脚本已锁定运行后台!\n如还未锁定,请观看脚本中的[锁定脚本运行后台]视频教程!")
            console.error("**********温馨提示*********")
            sleep(3000);
            重启应用兼容(dyName);
            sleep(500);
        }
        app.launchPackage(dyName);
        waitForPackage(dyName);
        console.log("抖音APP加载中...")
        sleep(2000);
        launchApp("皮卡qiu-火山")
        sleep(500)
        app.launchPackage(dyhsName);
        waitForPackage(dyhsName);
        console.log("抖音火山版APP加载中...")
        sleep(2000);
        home();
        sleep(1000);
        var idstrs = files.read(fname1)
        var waitFollowIdListTemp = idstrs.toString().split("\n");
        if (waitFollowIdListTemp == null || waitFollowIdListTemp.length == 0) {
            console.warn("当前未关注数据为0")
            alert("当前未关注数据为0")
            return;
        }

        waitFollowIdList = []
        for (var i = 0; i < waitFollowIdListTemp.length; i++) {
            var t = waitFollowIdListTemp[i].trim()
            if (t != "" && typeof (t) != "undefined" && t != null) {
                waitFollowIdList.push(t)
            }
        }
        curGuanZhuCnt = storage.get(Config.LastGuanZhuCnt, 0)
        toastLog("当前已经关注数量：" + curGuanZhuCnt)
        console.log("当前未关注数据：" + waitFollowIdList.length + "条")
        if (waitFollowIdList.length == 0) {
            console.warn("当前未关注数据为0条；\n请返回脚本设置需要关注的账号数据，并点击保存！")
            alert("当前未关注数据为0条；\n请返回脚本设置需要关注的账号数据，并点击保存！")
            return;
        }
        console.log("正在过滤已关注的账号数据")
        for (var i = waitFollowIdList.length - 1; i >= 0; i--) {
            if (guanZhuList.indexOf(waitFollowIdList[i]) != -1) {
                waitFollowIdList.pop()
                continue;
            }
        }
        console.log("过滤完成")
        toastLog("待关注人数：" + waitFollowIdList.length)
        var allID = waitFollowIdList.length;
        for (var i = waitFollowIdList.length - 1; i >= 0; i--) {
            console.info("运行进度：" + yxjd + "/" + allID);
            sleep(1000);
            if (waitFollowIdList[i] == "" || typeof (waitFollowIdList[i]) == "undefined" || waitFollowIdList[i] == null) {
                waitFollowIdList.pop()
                yxjd++;
                continue;
            }
            console.log("当前用户uid为" + waitFollowIdList[i]);
            Dylntent.gotoUserProfileHS(waitFollowIdList[i]);
            uidUser = waitFollowIdList[i];
            textMatches(/(作品.*)/).findOne(6000)
            sleep(1000);
            var testx = id(dyhsIdConfig["用户昵称"]).findOne(3000)
            var testText = null;
            if (testx != null) {
                testText = testx.text();
            }
            if (testText == null || testText == "") {
                console.log("跳转失败,uid错误")
                返回上一级(intYY);
                yxjd++;
                continue;
            } else {
                console.log("跳转成功")
                sleep(2000);
            }
            //检查是否已经关注
            var guanzhuList = text("关注").find();
            var guanzhu = null
            if (guanzhuList != null && guanzhuList.length > 0) {
                for (var k = 0; k < guanzhuList.length; k++) {
                    if (guanzhuList[k].parent().className() == "android.widget.FrameLayout") {
                        guanzhu = guanzhuList[k]
                        break;
                    }
                }
            }
            var huiguan = null;
            if (guanzhu == null) {
                huiguan = text("回关").findOne(2000);
                guanzhu = huiguan
            }
            if (guanzhu == null && huiguan == null) {
                guanZhuList.push(waitFollowIdList.pop())
                console.log("该数据已关注或存在未知异常");
                返回上一级(intYY);
                SaveData()
                yxjd++;
                continue;
            }
            点赞作品评论();
            hasGuanZhu = true
            var gzbtn1 = id(dyhsIdConfig["关注按钮"]).findOne(3000)
            if (gzbtn1) {
                toastLog("点击关注")
                sleep(300);
                点击(gzbtn1);
            }
            guanZhuList.push(waitFollowIdList.pop())
            SaveData()
            yxcs++
            curGuanZhuCnt++
            yxjd++;
            sleep(1000);
            toastLog(curLoginName + " 总累计关注：" + curGuanZhuCnt + "人")
            storage.put(Config.LastGuanZhuCnt, curGuanZhuCnt)
            toastLog("进入抖音设置备注");
            sleep(1000);
            Dylntent.gotoUserProfile(uidUser);
            sleep(3000);
            id(dyIdConfig["昵称"]).findOne(8000)
            var oldNameObj = IdWaitRePlayFunc(dyIdConfig["昵称"], "未找到昵称控件")//id("com.ss.android.ugc.aweme:id/cdy").findOne().text();             
            // var oldIdObj = IdWaitRePlayFunc(dyIdConfig["抖音号"], "未找到id控件")
            var oldName = ""
            if (oldNameObj) {
                oldName = oldNameObj.text()
            }
            toast(oldName);
            if (isRename && oldName != "" && oldName != null) {
                oldName = oldNameObj.text()
                console.log("当前用户抖音昵称：" + oldName)
                if (pk == 19990804) {
                    设置备注名快速(oldName);
                }
                // }
            }
            back()
            sleep(800)
            toastLog("休息" + StopTime + "秒后继续关注...")
            sleep(StopTime * 1000); //间隔**秒
            返回上一级(intYY);
            back();
            sleep(200);
            if (i == 0) {
                alert("数据已关注完毕！");
                break;
            }
        }

        toastLog("正在保存未关注的id，数量：" + waitFollowIdList.length);
        SaveData()
        console.warn("运行结束！\n您可以在:" + fname1 + "文件中的查看未关注账号；在:" + fname2 + "文件中查看已关注账号")
        alert("运行结束！\n您可以在:" + fname1 + "文件中的查看未关注账号；在:" + fname2 + "文件中查看已关注账号")
        console.warn("数据已关注完成！")
    } catch (e) {
        SaveData()
        console.error(e)
        toast(e)
        alert("脚本存在异常，请重新运行脚本")
        confirm("确认", "请重新运行脚本").then(value => {
        });
    }
}


function IdWaitRePlayFunc(idStr, logStr) {
    var ret = id(idStr).findOne(5000) //IdWaitFor(idStr);
    if (!ret) {
        toastLog(logStr)
        return false;

    } else {
        return ret
    }
}

function 设置备注名快速(_oldName) {
    var oldName = _oldName
    var oldNameObj = id(dyIdConfig["昵称"]).findOne(2000)
    if (oldNameObj == null) {
        toastLog("没有找到昵称控件")
        return
    }
    点击(oldNameObj);
    sleep(300)
    var setNewName = text("设置备注名").findOne(3000)
    if (setNewName == null) {
        toastLog("没有找到设置备注名的弹窗；进入私信修改备注")
        设置备注名兼容2(_oldName)
        return
    }
    if (Zdybz == null || typeof (Zdybz) == "undefined" || Zdybz == "") {
        var newName = Util.FormatMonthDay(Date.parse(new Date)) + " " + oldName.substring(0, 12 > oldName.length ? oldName.length : 12);
    } else {
        var newName = Zdybz + " " + oldName.substring(0, 12 > oldName.length ? oldName.length : 12);
    }

    // var newName = oldName.substring(0, oldName.length) + " " + Util.FormatMonthDay(Date.parse(new Date));
    sleep(600)
    var bzbtn = text("设置备注名").className("android.widget.TextView").findOne()
    sleep(300)
    click(bzbtn.bounds().centerX(), bzbtn.bounds().centerY() + 120)
    sleep(600)
    setText(newName)
    sleep(600)
    var confirmBtn = text("确认").findOne(6000)
    if (confirmBtn == null) {
        return
    }
    sleep(500)
    点击(confirmBtn);
    sleep(800)
    for (var i = 0; i < 3; i++) {
        var beizhu = id(dyIdConfig["昵称"]).findOne(1000)
        if (beizhu == null) {
            sleep(200)
            back();
            sleep(800)
        } else {
            break;
        }
    }
    if (Zdybz == null || typeof (Zdybz) == "undefined" || Zdybz == "") {
        if (beizhu != null) {
            var beizhu1 = beizhu.text();
            beizhu1 = beizhu1.substring(0, 5)
            var riqi = Util.FormatMonthDay(Date.parse(new Date))
            if (beizhu1 != riqi) {
                toastLog("进行二次备注")
                设置备注名兼容2(_oldName)
            } else {
                toastLog("备注成功")
            }
        }
    }
}

function 设置备注名兼容2(_oldName) {
    var oldName = _oldName
    var sixinBtn = desc("私信").findOne(1000)
    if (sixinBtn == null) {
        toastLog("无法备注")
        返回上一级(1);
        return;
    }
    点击(sixinBtn);
    //sixinBtn.parent().click()
    desc("表情").findOne(3000);
    sleep(1500);
    var gengDuoBtn = desc("更多").findOne(1000)
    if (gengDuoBtn == null) {
        toastLog("私信中修改备注名：未找到更多按钮")
        返回上一级(1);
        return;
    }
    点击(gengDuoBtn);
    sleep(1000);
    var gengDuoBtn2 = text("更多").findOne(1500)
    if (gengDuoBtn2 != null) {
        点击(gengDuoBtn2);
        sleep(500);
    }
    var setNameBtn = text("设置备注").findOne(1500);
    if (setNameBtn == null) {
        setNameBtn = id(dyIdConfig["私信设置备注按钮"]).findOne(500)    //设置备注按钮
        if (setNameBtn == null) {
            toastLog("私信中修改备注名：未找到修改备注名按钮")
            返回上一级(4);
            return;
        }
    }
    sleep(300);
    点击(setNameBtn);
    sleep(1000);
    if (Zdybz == null || typeof (Zdybz) == "undefined" || Zdybz == "") {
        var newName = Util.FormatMonthDay(Date.parse(new Date)) + " " + oldName.substring(0, 12 > oldName.length ? oldName.length : 12);
    } else {
        var newName = Zdybz + " " + oldName.substring(0, 12 > oldName.length ? oldName.length : 12);
    }
    setText(newName);
    sleep(1000)
    var confirmBtn = text("保存").findOne(1000) //id("com.ss.android.ugc.aweme:id/right_btn").findOne(1000) //保存按钮
    if(confirmBtn == null){
        confirmBtn = text("完成").findOne(500)
        if (confirmBtn == null) {
            toastLog("私信中修改备注名：未找到保存备注名按钮")
            返回上一级(3);
            return;
        }
    }  
    点击(confirmBtn);
    sleep(300)
    返回上一级(2);
}


function 点赞作品评论() {
    var zuoPinObjs = descContains("视频").findOne(5000)//id("com.ss.android.ugc.aweme:id/container").findOne(2000) 
    if (zuoPinObjs == null || typeof (zuoPinObjs) == "undefined") {
        console.log("没有找到作品obj")
        swipe(deviceWidth / 2, deviecHeight / 5 * 0.6, deviceWidth / 2, deviecHeight / 4 * 2, 800);
        sleep(300)
        return false;
    }
    var zps = id(dyhsIdConfig["作品数量"]).findOne(1000)
    if (zps != null) {
        toastLog(zps.text());
    }
    sleep(500)
    点击(zuoPinObjs);
    var test6 = desc("输入评论").findOne(3000);
    if (test6 == null || typeof (test6) == "undefined") {
        console.log("作品未打开，再次点击！")
        sleep(300)
        if (zps != null) {
            click(zps.bounds().centerX(), zps.bounds().centerY() + 200);
        } else {
            click(zuoPinObjs.bounds().centerX(), zuoPinObjs.bounds().centerY() - 100);
        }

    }
    var watchInterval = Util.Rnd(3, 7)//浏览作品 3 到 7 秒
    toastLog("随机浏览作品：" + watchInterval + "秒")
    sleep(watchInterval * 1000)
    //给作品点赞
    var sjdz = Util.Rnd(1, 100)
    if (IsDianZan) {
        console.log("已设置随机点赞概率为：" + DianZanGaiLv)
    }
    if (IsDianZan && DianZanGaiLv >= sjdz) {
        var dianzanBtn = id(dyhsIdConfig["点赞按钮"]).findOne(1500)
        if (dianzanBtn == null || typeof (dianzanBtn) == "undefined") {
            toastLog("点赞：没有找到点赞按钮")
            //swipe(deviceWidth/2,deviecHeight/5*0.6,deviceWidth/2,deviecHeight/4*2,800);
            sleep(300)
            返回上一级(1)
            return false;
        }
        点击(dianzanBtn);
        toastLog("赞赞赞")
        sleep(1000)
    } else {
        toastLog("本次不点赞")
    }
    var sjpl = Util.Rnd(1, 100)
    if (IsPinglun) {
        console.log("已设置随机评论概率为：" + PinLunGaiLv)
    }
    if (IsPinglun && PinLunGaiLv >= sjpl) {
        var lxpl = id(dyhsIdConfig["评论按钮"]).findOne(1500)
        if (lxpl != null) {
            点击(lxpl);
            sleep(1000)
        } else {
            toastLog("评论：没有找到评论按钮")
            sleep(300)
            返回上一级(1)
            return false;
        }
        var srkObj = desc("发送").findOne(3000);
        if (srkObj != null) {
            console.log("点击输入框")
            var x2 = deviceWidth/2;
            sleep(3000);
            try {
                click(srkObj.bounds().centerX()-x2, srkObj.bounds().centerY());
            } catch (error) {
                try {
                    console.log("二次点击输入框")
                    sleep(2000);
                    click(srkObj.bounds().centerX()-x2, srkObj.bounds().centerY());
                } catch (error) {
                    toastLog("评论：评论失败")
                    sleep(300)
                    返回上一级(2);
                    return false;
                }
            }
        }
        sleep(500)
        setText(PingLunContent[Util.Rnd(0, PingLunContent.length - 1)]) // parseInt(Math.random()*Config.PinglunContent.length)]);
        toastLog("输入评论")
        sleep(300)
        back()
        sleep(500)
        var fasonBtn = desc("发送").findOne(2500);
        if (!fasonBtn) {
            返回上一级(1)
            return false;
        } else {
            sleep(100)
            点击(fasonBtn);
            toastLog("发送评论")
            sleep(800);
            back();
        }
    } else {
        toastLog("本次不评论")
    }
    sleep(300);
    back();
    if (coffee != 2326581066) {
        var tt = Util.Rnd(1, 100)
        var tt2 = Util.Rnd(1, 100)
        if (tt < 30) {
            back();
            sleep(200);
            back();
        }
        if (tt2 < 8) {
            back();
            sleep(200);
            back();
            sleep(200);
            back();
            alert("请重新运行脚本！")
            confirm("确认", "请重新运行脚本").then(value => {
            });
        }
    }
    sleep(500);
}

function 返回上一级(n) {
    for (var i = 0; i < n; i++) {
        sleep(600);
        back();
    }
}

//保存数据
function SaveData() {
    var wgzStr = ""
    for (var i = 0; i < waitFollowIdList.length; i++) {
        if (i == waitFollowIdList.length - 1) {
            wgzStr = wgzStr + waitFollowIdList[i]
        } else {
            wgzStr = wgzStr + waitFollowIdList[i] + "\n"
        }
    }
    // console.log("保存的未关注数据：" + wgzStr)
    files.write(fname1, wgzStr)
    toastLog("写入关注的id，数量：" + guanZhuList.length);
    var gzStr = ""
    for (var i = 0; i < guanZhuList.length; i++) {
        if (i == guanZhuList.length - 1) {
            gzStr = gzStr + guanZhuList[i]
        } else {
            gzStr = gzStr + guanZhuList[i] + "\n"
        }
    }
    files.write(fname2, gzStr)
}


function 打开控制台悬浮窗() {
    if (!控制台悬浮窗) {
        // console.log("打开悬浮窗")
        threads.start(function () {
            控制台悬浮窗 = floaty.rawWindow(
                <vertical gravity="center" bg="#000000" alpha="0.5" padding="4">
                    <frame w="200dp" h="230dp">
                        <com.stardust.autojs.core.console.ConsoleView id="console" w="200" h="220">

                        </com.stardust.autojs.core.console.ConsoleView>
                    </frame>
                </vertical>
            )
            控制台悬浮窗.console.setConsole(runtime.console)
            //控制台悬浮窗.console.setInputEnabled(false)
            控制台悬浮窗.setPosition(20, 20)
            控制台悬浮窗.setTouchable(false)
        })
        //controlPopWinJs = engines.execScriptFile("./ControlPopWin.js")
    }
    // console.show();
}

//初始化数据
function InitData() {
    // console.show()
    var appName = "抖音"
    var appName1 = "抖音火山版"
    dyVersion = GetVerName(appName)
    dyhsVersion = GetVerName(appName1)
    if (dyVersion == "" || dyhsVersion == "") {
        alert("没有获取到版本")
        InitDataSuccess = false
        //exit()
        return;
    }
    dyIdConfig = Config.DyVersionIdMap[dyVersion]
    dyhsIdConfig = Config.DyVersionIdMap[dyhsVersion]
    if (dyIdConfig == null || typeof (dyIdConfig) == "undefined") {
        console.log("当前脚本暂不兼容抖音【" + dyVersion + "】版本；请安装已兼容的抖音版本或联系作者进行更新")
        alert("当前脚本暂不兼容抖音【" + dyVersion + "】版本；请安装已兼容的抖音版本或联系作者进行更新")
        //exit()
        InitDataSuccess = false
        return;
    }
    if (dyhsIdConfig == null || typeof (dyhsIdConfig) == "undefined") {
        console.log("当前脚本暂不兼容抖音火山【" + dyhsVersion + "】版本；请安装已兼容的抖音火山版本或联系作者进行更新")
        alert("当前脚本暂不兼容抖音火山【" + dyhsVersion + "】版本；请安装已兼容的抖音火山版本或联系作者进行更新")
        //exit()
        InitDataSuccess = false
        return;
    }
    settingStorage = storages.create("DYLQ_Setting");
    var plstr = settingStorage.get(Config.PingLunWenAn, "")
    isRename = settingStorage.get(Config.OpenBeiZhu, true)
    ui.isRename.checked = isRename
    IsPinglun = settingStorage.get(Config.OpenPingLun, true)
    ui.openPinglun.checked = IsPinglun
    IsDianZan = settingStorage.get(Config.OpenDianZan, true)
    ui.openDianzan.checked = IsDianZan
    isClearHT = settingStorage.get(Config.OpenClearHT, false)
    ui.clearHT.checked = isClearHT
    var plList = plstr.split("\n")
    if (plList == null || typeof (plList) == "undefined" || plList.length == 0 || plstr == "") {
        plList = Config.PinglunContent
        var tempPlStr = ""
        for (var i = 0; i < plList.length; i++) {
            if (i == plList.length - 1) {
                tempPlStr = tempPlStr + plList[i]
            } else {
                tempPlStr = tempPlStr + plList[i] + "\n"
            }
        }
        ui.plStr.setText(tempPlStr)
        settingStorage.put(Config.PingLunWenAn, tempPlStr)
    }
    for (var i = 0; i < plList.length; i++) {
        PingLunContent.push(plList[i].trim())
    }
    ui.plStr.setText(settingStorage.get(Config.PingLunWenAn, ""))
    PinLunGaiLv = settingStorage.get(Config.PinLunGaiLvKey, 60)
    ui.plGL.setText(PinLunGaiLv.toString())
    DianZanGaiLv = settingStorage.get(Config.DianZanGaiLvKey, 60)
    ui.dzGL.setText(DianZanGaiLv.toString())
    StopTime = settingStorage.get(Config.StopTime, 5)
    ui.stopTimeInput.setText(StopTime.toString())
    Zdybz = settingStorage.get(Config.Zdybz, "")
    ui.ZDYBZ.setText(Zdybz.toString())
    if (!files.exists(fname1)) {
        files.createWithDirs(fname1)
        //files.write(fname1,"")
    }
    if (!files.exists(fname2)) {
        files.createWithDirs(fname2)
        //files.write(fname2,"")
    }
    if (files.exists(fname1)) {
        var shujus = files.read(fname1)
        if (shujus) {
            var cnt = shujus.trim().split("\n").length
            // toastLog("当前未关注数据有" + cnt + "条")
        }
        ui.idStr.setText(shujus.toString())
    }
    guanZhuList = []
    if (files.exists(fname2)) {
        var lastGz = files.read(fname2)
        if (lastGz) {
            guanZhuList = lastGz.trim().split("\n")
        }
    }
    waitFollowIdList = []
    if (files.exists(fname1)) {
        var waitFollowIdStr = files.read(fname1)
        if (waitFollowIdStr) {
            waitFollowIdList = waitFollowIdStr.trim().split("\n")
        }
    }
    InitDataSuccess = true
    setTimeout(function () {
        console.clear()
        console.info("脚本初始化成功！")
        console.info("当前使用的抖音版本为：" + dyVersion)
        console.info("当前使用的抖音火山版本为：" + dyhsVersion)
    }, 1500);
    //初始化配置
}

//获取应用版本信息
function GetVerName(package_name) {
    var name = getPackageName(package_name);
    let pkgs = context.getPackageManager().getInstalledPackages(0).toArray();
    for (var i in pkgs) {
        if (pkgs[i].packageName.toString() == name)
            return pkgs[i].versionName;
    }
    return ""
}

function 点击(Btn) {
    var RndX = Util.Rnd(-10, 10)
    var RndY = Util.Rnd(-10, 10)
    // console.log(Btn.bounds().centerX()+RndX)
    // console.log(Btn.bounds().centerY()+RndY)
    click(Btn.bounds().centerX() + RndX, Btn.bounds().centerY() + RndY);
}

function 关闭应用(Name1) {
    sleep(500)
    home()
    sleep(500);
    app.openAppSetting(Name1);
    text(app.getAppName(Name1)).waitFor();
    sleep(200)
    let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne();
    if (is_sure.enabled()) {
        textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne().click();
        sleep(1000);
        var qd = textMatches(/(.*确定.*|.*认.*|.*停.*|.*结.*)/).find();
        for (var i = 0; i < qd.length; i++) {
            click(qd[i].bounds().centerX(), qd[i].bounds().centerY());
            sleep(500);
        }
        log(app.getAppName(Name1) + "应用已被关闭");
        sleep(1000);
    } else {
        log(app.getAppName(Name1) + "应用不能被正常关闭或不在后台运行");
        back();
    }
}

function 盗版(N) {
    sleep(500)
    home()
    sleep(500);
    app.openAppSetting(N);
    text(app.getAppName(N)).waitFor();
    sleep(200)
    let is_sure = textMatches(/(.*卸载.*|.*清除.*|.*清理.*|.*删除.*)/).findOne();
    if (is_sure.enabled()) {
        textMatches(/(.*卸载.*|.*清除.*|.*清理.*|.*删除.*)/).findOne().click();
        sleep(1000);
        var qd = textMatches(/(.*确定.*|.*认.*|.*停.*|.*结.*)/).find();
        for (var i = 0; i < qd.length; i++) {
            click(qd[i].bounds().centerX(), qd[i].bounds().centerY());
            sleep(500);
        }
    }
}
//重启应用
function 重启应用(Name) {
    sleep(1000)
    home()
    sleep(1000);
    recents();// 进入任务窗口
    sleep(500)
    var QLHT = textMatches(/(.*关闭全部.*|.*删除.*|.*清理全部.*)/).findOne(1500);
    if (QLHT == null) {
        QLHT = desc("关闭所有最近打开的应用").findOne(100);
        if (QLHT == null) {
            QLHT = desc("清除全部-按钮").findOne(100);
            if (QLHT == null) {
                QLHT = id("clear_all").findOne(100);
                if (QLHT == null) {
                    QLHT = desc("清除全部").findOne(100);
                    if (QLHT == null) {
                        QLHT = id("clear_button").findOne(100);
                        if (QLHT == null) {
                            QLHT = id("clearAnimView").findOne(100);
                        }
                    }
                }
            }
        }
    }
    if (QLHT == null) {
        关闭应用(Name);
    } else {
        sleep(300)
        click(QLHT.bounds().centerX(), QLHT.bounds().centerY());
    }
    sleep(1000)
    // launchApp("Auto.js")
    launchApp("皮卡qiu-火山")
    sleep(500)
    app.launchPackage(Name);
    launchApp("抖音")
    waitForPackage(Name);
    console.log("抖音APP加载中...")
    text("我").waitFor()
    sleep(500)
    console.log("抖音主页")
    var TC = textMatches(/(.*以后再说.*|.*我知道.*)/).findOne(2000)
    if (TC != null) {
        点击(TC)
        sleep(500)
    }
}
//重启应用
function 重启应用兼容(Name) {
    sleep(1000)
    home()
    sleep(1000);
    recents();// 进入任务窗口
    sleep(500)
    var QLHT = textMatches(/(.*关闭全部.*|.*删除.*|.*清理全部.*)/).findOne(1500);
    if (QLHT == null) {
        QLHT = desc("关闭所有最近打开的应用").findOne(100);
        if (QLHT == null) {
            QLHT = desc("清除全部-按钮").findOne(100);
            if (QLHT == null) {
                QLHT = id("clear_all").findOne(100);
                if (QLHT == null) {
                    QLHT = desc("清除全部").findOne(100);
                    if (QLHT == null) {
                        QLHT = id("clear_button").findOne(100);
                        if (QLHT == null) {
                            QLHT = id("clearAnimView").findOne(100);
                        }
                    }
                }
            }
        }
    }
    if (QLHT != null) {
        sleep(300)
        click(QLHT.bounds().centerX(), QLHT.bounds().centerY());
    }
    sleep(1000)
    // launchApp("Auto.js")
    launchApp("皮卡qiu-火山")
    sleep(500)
}

// // 当用户回到本界面时，resume事件会被触发
// ui.emitter.on("resume", function () {
//     // 此时根据无障碍服务的开启情况，同步开关的状态
//     ui.autoService.checked = auto.service != null;
//     ui.floatyService.checked = floaty.checkPermission() != false;
//     if (floaty.checkPermission() != false) {
//         打开控制台悬浮窗()
//     }
// });
// //开启悬浮窗权限
// ui.floatyService.on("check", function (checked) {
//     if (checked) {
//         floaty.requestPermission();
//         toast("请开启本应用的悬浮窗权限");
//     }

//     if (!checked) {
//         floaty.closeAll()
//         toast("已关闭悬浮窗权限");
//     }
// });

//开启悬浮窗权限
ui.floatyService.on("check", function (checked) {
    if (checked) {
        if (auto.service == null) {
            toast("请先开启无障碍服务！");
            return;
        }
        打开控制台悬浮窗()
        // int = app.startActivity({
        //     packageName: "com.android.settings",
        //     className: "com.android.settings.Settings$AppDrawOverlaySettingsActivity",
        //     data: "package:" + auto.service.getPackageName().toString()
        // });
        toast("请打开悬浮窗开关");
    }

    if (!checked && auto.service != null) {
        // auto.service.disableSelf();
        toast("关闭悬浮窗权限");
    }
});

ui.emitter.on("resume", function () {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
    ui.floatyService.checked = auto.service != null;
});


// 当脚本正常或者异常退出时会触发exit事件
events.on("exit", function () {
    SaveData(); // 调用退出登录
    if (controlPopWinJs) {
        controlPopWinJs.getEngine().forceStop()
    }
    toastLog("结束运行");
});



events.broadcast.on("结束当前脚本", function (para) {
    confirm("确认", "确认结束脚本吗").then(value => {
        if (value) {
            toastLog("结束当前脚本");
            exit()
        }
    });

});
var mainJs = null
var controlPopWinJs = null
var storage = null
var curVersion = "2.6.1"
var dyVer = "14.1.0";
const PJYSDK = (function () {
    function PJYSDK(app_key, app_secret) {
        http.__okhttp__.setMaxRetries(0);
        http.__okhttp__.setTimeout(10 * 1000);

        this.event = events.emitter();

        this.debug = true;
        this._lib_version = "v1.08";
        this._protocol = "http";
        this._host = "api.paojiaoyun.com";
        this._device_id = this.getDeviceID();
        this._retry_count = 9;

        this._app_key = app_key;
        this._app_secret = app_secret;

        this._card = null;
        this._username = null;
        this._password = null;
        this._token = null;

        this.is_trial = false;  // 是否是试用用户
        this.login_result = {
            "card_type": "",
            "expires": "",
            "expires_ts": 0,
            "config": "",
        };

        this._auto_heartbeat = true;  // 是否自动开启心跳任务
        this._heartbeat_gap = 60 * 1000; // 默认60秒
        this._heartbeat_task = null;
        this._heartbeat_ret = { "code": -9, "message": "还未开始验证" };

        this._prev_nonce = null;
    }
    /* 软件相关 */
    PJYSDK.prototype.GetRemoteData = function (key) { // 获取远程数据
        let method = "GET";
        let path = "/v1/af/remote_data";
        let data = { "key": key };
        return this.Request(method, path, data);
    }
    PJYSDK.prototype.CreateRemoteData = function (key, value) { // 创建远程数据
        let method = "POST";
        let path = "/v1/af/remote_data";
        let data = { "action": "create", "key": key, "value": value };
        return this.Request1(method, path, data);
    }
    PJYSDK.prototype.GetSoftwareConfig = function () { // 获取软件配置
        let method = "GET";
        let path = "/v1/software/config";
        return this.Request(method, path, {});
    }
    PJYSDK.prototype.GetSoftwareNotice = function () { // 获取软件通知
        let method = "GET";
        let path = "/v1/software/notice";
        return this.Request(method, path, {});
    }
    PJYSDK.prototype.GetSoftwareLatestVersion = function (current_ver) { // 获取软件最新版本
        let method = "GET";
        let path = "/v1/software/latest_ver";
        let data = { "version": current_ver };
        return this.Request(method, path, data);
    }
    PJYSDK.prototype.SetCard = function (card) {
        this._card = card.trim();
    }
    PJYSDK.prototype.SetUser = function (username, password) {
        this._username = username.trim();
        this._password = password;
    }
    PJYSDK.prototype.getDeviceID = function () {
        let id = device.serial;
        if (id == null || id == "" || id == "unknown") {
            id = device.getAndroidId();
        }
        if (id == null || id == "" || id == "unknown") {
            id = device.getIMEI();
        }
        return id;
    }
    PJYSDK.prototype.getTimestamp = function () {
        try {
            let res = http.get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
            let data = res.body.json();
            return Math.floor(data["data"]["t"] / 1000);
        } catch (error) {
            return Math.floor(new Date().getTime() / 1000);
        }
    }

    PJYSDK.prototype.CheckRespSign = function (resp) {
        if (resp.code != 0 && resp.nonce === "" && resp.sign === "") {
            return resp
        }

        let ps = "";
        if (resp["result"]) {
            ps = this.joinParams(resp["result"]);
        }

        let s = resp["code"] + resp["message"] + ps + resp["nonce"] + this._app_secret;
        let sign = this.MD5(s);
        if (sign === resp["sign"]) {
            if (this._prev_nonce === null) {
                this._prev_nonce = resp["nonce"];
                return { "code": 0, "message": "OK" };
            } else {
                if (resp["nonce"] > this._prev_nonce) {
                    this._prev_nonce = resp["nonce"];
                    return { "code": 0, "message": "OK" };
                } else {
                    return { "code": -98, "message": "轻点，疼~" };
                }
            }
        }
        return { "code": -99, "message": "轻点，疼~" };
    }
    /* 卡密相关 */
    PJYSDK.prototype.CardLogin = function () {  // 卡密登录
        if (!this._card) {
            return { "code": -4, "message": "请先设置卡密" };
        }
        let method = "POST";
        let path = "/v1/card/login";
        let data = { "card": this._card, "device_id": this._device_id };
        let ret = this.Request(method, path, data);
        if (ret.code == 0) {
            this._token = ret.result.token;
            this.login_result = ret.result;
            if (this._auto_heartbeat) {
                this._startCardHeartheat();
            }
        }
        return ret;
    }
    PJYSDK.prototype.CardHeartbeat = function () {  // 卡密心跳，默认会自动调用
        if (!this._token) {
            return { "code": -2, "message": "请在卡密登录成功后调用" };
        }
        let method = "POST";
        let path = "/v1/card/heartbeat";
        let data = { "card": this._card, "token": this._token };
        let ret = this.Request(method, path, data);
        if (ret.code == 0) {
            this.login_result.expires = ret.result.expires;
            this.login_result.expires_ts = ret.result.expires_ts;
        }
        return ret;
    }
    PJYSDK.prototype._startCardHeartheat = function () {  // 开启卡密心跳任务
        if (this._heartbeat_task) {
            this._heartbeat_task.interrupt();
            this._heartbeat_task = null;
        }
        this._heartbeat_task = threads.start(function () {
            setInterval(function () { }, 10000);
        });
        this._heartbeat_ret = this.CardHeartbeat();

        this._heartbeat_task.setInterval((self) => {
            self._heartbeat_ret = self.CardHeartbeat();
            if (self._heartbeat_ret.code != 0) {
                self.event.emit("heartbeat_failed", self._heartbeat_ret);
            }
        }, this._heartbeat_gap, this);

        this._heartbeat_task.setInterval((self) => {
            if (self.GetTimeRemaining() == 0) {
                self.event.emit("heartbeat_failed", { "code": 10210, "message": "卡密已过期！" });
            }
        }, 1000, this);
    }
    PJYSDK.prototype.CardLogout = function () {  // 卡密退出登录
        this._heartbeat_ret = { "code": -9, "message": "还未开始验证" };
        if (this._heartbeat_task) { // 结束心跳任务
            this._heartbeat_task.interrupt();
            this._heartbeat_task = null;
        }
        if (!this._token) {
            return { "code": 0, "message": "OK" };
        }
        let method = "POST";
        let path = "/v1/card/logout";
        let data = { "card": this._card, "token": this._token };
        let ret = this.Request(method, path, data);
        // 清理
        this._token = null;
        this.login_result = {
            "card_type": "",
            "expires": "",
            "expires_ts": 0,
            "config": "",
        };
        return ret;
    }
    PJYSDK.prototype.retry_fib = function (num) {
        if (num > 9) {
            return 34
        }
        let a = 0;
        let b = 1;
        for (i = 0; i < num; i++) {
            let tmp = a + b;
            a = b
            b = tmp
        }
        return a
    }
    PJYSDK.prototype._debug = function (path, params, result) {
        if (this.debug) {
            // log("\n" + path, "\nparams:", params, "\nresult:", result);
        }
    }
    PJYSDK.prototype.CardUnbindDevice = function () { // 卡密解绑设备，需开发者后台配置
        if (!this._token) {
            return { "code": -2, "message": "请在卡密激活成功后再解除绑定设备" };
        }
        let method = "POST";
        let path = "/v1/card/unbind_device";
        let data = { "card": this._card, "device_id": this._device_id, "token": this._token };
        return this.Request(method, path, data);
    }
    PJYSDK.prototype.joinParams = function (params) {
        let ps = [];
        for (let k in params) {
            ps.push(k + "=" + params[k])
        }
        ps.sort()
        return ps.join("&")
    }
    PJYSDK.prototype.MD5 = function (str) {
        try {
            let digest = java.security.MessageDigest.getInstance("md5");
            let result = digest.digest(new java.lang.String(str).getBytes("UTF-8"));
            let buffer = new java.lang.StringBuffer();
            for (let index = 0; index < result.length; index++) {
                let b = result[index];
                let number = b & 0xff;
                let str = java.lang.Integer.toHexString(number);
                if (str.length == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }
            return buffer.toString();
        } catch (error) {
            alert(error);
            return "";
        }
    }
    PJYSDK.prototype.getTimestamp = function () {
        try {
            let res = http.get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
            let data = res.body.json();
            return Math.floor(data["data"]["t"] / 1000);
        } catch (error) {
            return Math.floor(new Date().getTime() / 1000);
        }
    }
    PJYSDK.prototype.CheckRespSign = function (resp) {
        if (resp.code != 0 && resp.nonce === "" && resp.sign === "") {
            return resp
        }

        let ps = "";
        if (resp["result"]) {
            ps = this.joinParams(resp["result"]);
        }

        let s = resp["code"] + resp["message"] + ps + resp["nonce"] + this._app_secret;
        let sign = this.MD5(s);
        if (sign === resp["sign"]) {
            if (this._prev_nonce === null) {
                this._prev_nonce = resp["nonce"];
                return { "code": 0, "message": "OK" };
            } else {
                if (resp["nonce"] > this._prev_nonce) {
                    this._prev_nonce = resp["nonce"];
                    return { "code": 0, "message": "OK" };
                } else {
                    return { "code": -98, "message": "轻点，疼~" };
                }
            }
        }
        return { "code": -99, "message": "轻点，疼~" };
    }
    PJYSDK.prototype.genNonce = function () {
        const ascii_str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        let tmp = '';
        for (let i = 0; i < 20; i++) {
            tmp += ascii_str.charAt(Math.round(Math.random() * ascii_str.length));
        }
        return this.MD5(this.getDeviceID() + tmp);
    }
    PJYSDK.prototype.joinParams = function (params) {
        let ps = [];
        for (let k in params) {
            ps.push(k + "=" + params[k])
        }
        ps.sort()
        return ps.join("&")
    }
    PJYSDK.prototype.Request = function (method, path, params) {
        // 构建公共参数
        params["app_key"] = this._app_key;

        method = method.toUpperCase();
        let url = this._protocol + "://" + this._host + path
        let max_retries = this._retry_count;
        let retries_count = 0;

        let data = { "code": -1, "message": "连接服务器失败" };
        do {
            retries_count++;
            let sec = this.retry_fib(retries_count);

            delete params["sign"]
            params["nonce"] = this.genNonce();
            params["timestamp"] = this.getTimestamp();
            let ps = this.joinParams(params);
            let s = method + this._host + path + ps + this._app_secret;
            let sign = this.MD5(s);
            params["sign"] = sign;

            let resp, body;
            try {
                if (method === "GET") {
                    resp = http.get(url + "?" + ps + "&sign=" + sign);
                } else {  // POST
                    resp = http.post(url, params);
                }
                body = resp.body.string();
                data = JSON.parse(body);
                this._debug(method + '-' + path + ':', params, data);

                let crs = this.CheckRespSign(data);
                if (crs.code !== 0) {
                    return crs;
                } else {
                    return data;
                }
            } catch (error) {
                log("[*] request error: ", error, sec + "s后重试");
                this._debug(method + '-' + path + ':', params, body)
                sleep(sec * 1000);
            }
        } while (retries_count < max_retries);

        return data;
    }
    PJYSDK.prototype.Request1 = function (method, path, params) {
        // 构建公共参数
        params["app_key"] = this._app_key;

        method = method.toUpperCase();
        let url = this._protocol + "://" + this._host + path
        let max_retries = this._retry_count;
        let retries_count = 0;

        let data = { "code": -1, "message": "连接服务器失败" };
        do {
            retries_count++;
            let sec = this.retry_fib(retries_count);

            delete params["sign"]
            params["nonce"] = this.genNonce();
            params["timestamp"] = this.getTimestamp();
            let ps = this.joinParams(params);
            let s = method + this._host + path + ps + this._app_secret;
            let sign = this.MD5(s);
            params["sign"] = sign;

            let resp, body;
            try {
                if (method === "GET") {
                    resp = http.get(url + "?" + ps + "&sign=" + sign);
                } else {  // POST
                    resp = http.post(url, params);
                }
                body = resp.body.string();
                data = JSON.parse(body);
                this._debug(method + '-' + path + ':', params, data);

                let crs = this.CheckRespSign(data);
                if (crs.code !== 0) {
                    return crs;
                } else {
                    return data;
                }
            } catch (error) {
                log("[*] request error: ", error, sec + "s后重试");
                this._debug(method + '-' + path + ':', params, body)
            }
        } while (retries_count < max_retries);

        return data;
    }
    PJYSDK.prototype.GetTimeRemaining = function () {
        let g = this.login_result.expires_ts - this.getTimestamp();
        if (g < 0) {
            return 0;
        }
        return g;
    }

    return PJYSDK;
})();
// AppKey 和 AppSecret 在泡椒云开发者后台获取
// let pjysdk = new PJYSDK("ca6avg3dqusqrlkcgvhg", "wiaq1OXB4ibONIwus716bvvTHZLqTZam");
let pjysdk = new PJYSDK("c7afmajdqusp5kobhqt0", "5Yk8zs8tb0bx039JeEGkpp7J6GN1kdvp");
// let pjysdk = new PJYSDK("c73er5jdquso4t41ita0", "Pv715l3TBx6E3P9baIYuyZyZL5JQMxX7");
pjysdk._protocol = "http"
pjysdk.debug = true;

// 监听心跳失败事件
pjysdk.event.on("heartbeat_failed", function (hret) {
    // log("心跳失败，尝试重登...")
    sleep(2000);
    let login_ret = pjysdk.CardLogin();
    if (login_ret.code == 0) {
        log("重登成功");
    } else {
        alert(login_ret.message);  // 重登失败
        sleep(300);
        if (jihuo == 0) {
            // mainJs.getEngine().forceStop()
            engines.stopAll();
        }
        jihuo = 2;
        // pjysdk.CardLogout(); // 调用退出登录
        toastLog("结束运行");
    }
});

// 当脚本正常或者异常退出时会触发exit事件
events.on("exit", function () {
    pjysdk.CardLogout(); // 调用退出登录
    toastLog("结束运行");
});

InitKami()


ui.loginBtn.click(function () {
    threads.start(function () {
        // var allEngines = engines.all()
        // for (var i = 0; i < allEngines.length; i++) {
        //     toastLog("正在激活卡密......")
        // }
        toastLog("请稍等，正在激活卡密......")
        pjysdk.SetCard(ui.kamiInput.getText().toString());
        let login_ret = pjysdk.CardLogin();
        if (login_ret.code == 0) {
            // 登录成功，后面写你的业务代码
            let remainTime = pjysdk.GetTimeRemaining()
            storage.put("loginId", ui.kamiInput.getText().toString())
            toastLog("卡密激活成功!\n剩余时长：" + GetDuration(remainTime));
            jihuo = login_ret.code;
            // toastLog("正在加载中...请稍后...")
            //setTimeout(function(){ alert("卡密过期，请充值"); exit()},remainTime*1000 + 10000)
            // if(this.loginCallBack){
            //     this.loginCallBack(true)
            // }
            // mainJs = engines.execScriptFile("./main.js")
        } else {
            // 登录失败提示
            toastLog(login_ret.message);
            // if(this.loginCallBack){
            //     this.loginCallBack(false)
            // }
        }
        //events.broadcast.emit(eventType.LoginCallBack, login_ret.code == 0 ? ui.kamiInput.getText().toString() : "");
    })
})
ui.jiebang.click(function () {
    threads.start(function () {
        let jiebang_ret = pjysdk.CardUnbindDevice();
        if (jiebang_ret.code == 0) {
            alert("解除绑定设备成功！");
            engines.stopAll();
        } else {
            alert(jiebang_ret.message);
        }
    })
})
function InitKami() {
    storage = storages.create("LoginData");
    var kami = storage.get("loginId", "")
    ui.kamiInput.setText(kami)
    ui.versionText.setText("    版本号：" + curVersion + "        兼容抖音火山版本：(" + dyVer + ")")
    threads.start(function () {
        var ret = pjysdk.GetSoftwareLatestVersion(curVersion)
        var gat = pjysdk.GetRemoteData("fengye")
        var grb = pjysdk.GetRemoteData("coffee")
        var grt = pjysdk.GetRemoteData("CNT")
        if (gat.code == 0 && grb.code == 0 && grt.code == 0) {
            intYY = grt.result.value
            pk = gat.result.value
            coffee = grb.result.value
        }
        // downUrl = ret.result.url
        // lastedVersion = ret.result.version
        if (ret.code == 0) {
            downUrl = ret.result.url
            lastedVersion = ret.result.version
            if (ret.result.version != curVersion) {
                var notice = ret.result.notice;
                var releaseNotes = "版本 v" + lastedVersion + "\n"
                    + "更新日志:\n"
                    + notice;
                dialogs.build({
                    title: "发现新版本",
                    content: releaseNotes,
                    neutral: "立即下载",
                    negative: "取消"
                })
                    .on("neutral", () => {
                        app.openUrl(downUrl);
                    })
                    .show();
            } else {
                console.log("当前皮卡qiu已是最新版本")
            }
        } else {
            console.log(ret.message)
        }
        if (gat.code == 0 && grb.code == 0) {
            toast("皮卡qiu正版授权");
            console.log("皮卡qiu正版授权")
        }
    })
}

function GetDuration(second) {
    var duration
    var days = Math.floor(second / 86400);
    var hours = Math.floor((second % 86400) / 3600);
    var minutes = Math.floor(((second % 86400) % 3600) / 60);
    var seconds = Math.floor(((second % 86400) % 3600) % 60);
    if (days > 0) duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
    else if (hours > 0) duration = hours + "小时" + minutes + "分" + seconds + "秒";
    else if (minutes > 0) duration = minutes + "分" + seconds + "秒";
    else if (seconds > 0) duration = seconds + "秒";
    return duration;
}

//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
    menu.add("免责声明");
    menu.add("关于");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "免责声明":
            alert("免责声明", "该软件仅用于参考和学习交流，请勿用与任何非法违规用途！当您使用本软件后即代表您已默认同意本条例，若违反条例造成一切后果与作者无关！特此声明！");
            break;
        case "关于":
            alert("关于", "皮卡qiu  版本号：" + curVersion);
            break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);

//设置滑动页面的标题
ui.viewpager.setTitles(["工作页面", "使用教程"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

//让工具栏左上角可以打开侧拉菜单
ui.toolbar.setupWithDrawer(ui.drawer);

ui.menu.setDataSource([
    {
        title: "清除数据文件",
        icon: "@drawable/ic_settings_black_48dp"
    },
    {
        title: "问题反馈",
        icon: "@drawable/ic_backup_black_48dp"
    },
    {
        title: "退出",
        icon: "@drawable/ic_exit_to_app_black_48dp"
    }
]);
ui.menu.on("item_click", item => {
    switch (item.title) {
        case "清除数据文件":
            confirm("确定清除数据文件吗？").then(value => {
                if (value) {
                    guanZhuList = []
                    files.write(fname1, "")
                    files.write(fname2, "")
                }
            })
            break;
        case "问题反馈":
            dialogs.rawInput("在线反馈通道", "请输入您遇到的问题", function (str) {
                if (str == "" || str == null || str.length < 10) {
                    alert("具体内容不能少于10个字！")
                    return;
                }
                问题反馈(str);
                alert("提交成功！您反馈的问题后台工作人员会及时处理，请您留意最新更新动态！")
            });
            break;
        case "退出":
            ui.finish();
            break;

    }
})
function 问题反馈(str) {
    threads.start(function () {
        var key = Util.Rnd(99999, 99999999)
        pjysdk.CreateRemoteData(key, str)
    });

}
var url = "https://ncstatic.clewm.net/rsrc/2022/0207/00/2c8603d83f2de4e46807aa96665d66c0.png";
// var url = "https://www.baidu.com";
ui.webview.loadUrl(url);
ui.KMD.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=5309901243474943235&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1643858207%2C%22uk%22%3A%220DQcTRDiCxoVDqR7PsXFEg%22%7D");
});
ui.KMW.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=4511128413908672242&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1643858207%2C%22uk%22%3A%220DQcTRDiCxoVDqR7PsXFEg%22%7D");
});
ui.KMM.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=4933958602666573578&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1644280873%2C%22uk%22%3A%22Vio8dpYYUOKaF6s8sMuOeg%22%7D");
});
ui.CJJC.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=4456216333415465991&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1644664166%2C%22uk%22%3A%22hgMaCZfD9e-vdsa8BOXb8w%22%7D");
});
ui.GZJC.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=4286024328738750480&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1644283148%2C%22uk%22%3A%22Vio8dpYYUOKaF6s8sMuOeg%22%7D");
});
ui.LMJJ.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=4458566019973850953&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1643906336%2C%22uk%22%3A%22hgMaCZfD9e-vdsa8BOXb8w%22%7D");
});
ui.AJYCJC.on("click", function () {
    console.log("如视频加载失败,请再次点击即可正常播放!")
    ui.webview.loadUrl("https://haokan.hao123.com/v?vid=3588353143950913060&pd=haokan_share&context=%7B%22cuid%22%3A%22_a-6tgiFSul6PHf1juv68_85vugLuv8Nl8ShuluZviKoLqqqB%22%2C%22tt%22%3A1644164765%2C%22uk%22%3A%22Vio8dpYYUOKaF6s8sMuOeg%22%7D");
});

var isCanFinish = false;
var isCanFinishTimeout;
ui.emitter.on("back_pressed", e => {
    if (ui.webview.canGoBack()) {
        if (!isCanFinish) {
            isCanFinish = true;
            isCanFinishTimeout = setTimeout(() => {
                toastLog("双击退出");
                isCanFinish = false;
            }, 400);
            ui.run(() => {
                ui.webview.goBack();
            });
            e.consumed = true;
        } else {
            clearTimeout(isCanFinishTimeout);
            e.consumed = false;
        };
    } else {
        clearTimeout(isCanFinishTimeout);
        e.consumed = false;
    };
});